package com.wp.file.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.wp.file.common.BaseContext;
import com.wp.file.common.R;
import com.wp.file.dao.WarehouseMapper;
import com.wp.file.pojo.Recycle;
import com.wp.file.pojo.Warehouse;
import com.wp.file.service.RecycleService;
import com.wp.file.service.WarehouseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/recycle")
public class RecycleController {
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private RecycleService recycleService;


    @DeleteMapping("/delete")
    public R<String> delete(@RequestBody Warehouse warehouse){
        Long currentId = BaseContext.getCurrentId();
        if(warehouse.getUserId().equals(currentId)){
            Recycle recycle = new Recycle();
            recycle.setDeletedId(warehouse.getId());
            recycle.setName(warehouse.getDisplayName());
            recycle.setUserId(currentId);
            recycleService.save(recycle);
            warehouseService.removeById(warehouse.getId());
            return R.success(warehouse.getDisplayName()+"已删除!");
        }
        return R.error("用户错误!");
    }
    
    @GetMapping("/getlist")
    public R<List<Recycle>> getList (){
        LambdaQueryWrapper<Recycle> lqw = new LambdaQueryWrapper<>();
        Long currentId = BaseContext.getCurrentId();
        lqw.eq(Recycle::getUserId,currentId);
        lqw.orderByDesc(Recycle::getDeleteTime);
        List<Recycle> recycleList = recycleService.list(lqw);
        return R.success(recycleList);
    }
    
    @PostMapping("/recovery")
    public R<String> recovery(@RequestBody Recycle recycle){
        Long currentId = BaseContext.getCurrentId();
        if(currentId.equals(recycle.getUserId())){
            SqlRunner.db().update("update warehouse set delete_flag = 0 where warehouse.id="
                    +recycle.getDeletedId());
            recycleService.removeById(recycle.getId());
            return R.success("恢复成功");
        }
        return R.error("用户错误!");
    }
}
